// GlobalContext.js
import React, { createContext, useContext, useReducer } from 'react';
import AsyncStorage from "@react-native-async-storage/async-storage";

const GlobalContext = createContext();
// AsyncStorage.removeItem("TOKEN")

const initialState = {
  // 初始状态
  userInfo: {
    userId:'',
  },
  token:'',
  primaryVersionCode:'2',//第一版本号
  secondryVersionCode:'0',//第二版本号
  tertiaryVersionCode:'0',//第三版本号

};

// AsyncStorage.setItem("TOKEN",'9624ce3a370548e8f9f057d49bcc70ef')




const globalReducer = (state, action) => {
  switch (action.type) {
    case 'SET_USER':
      return { ...state, userInfo: action.payload };
    case 'SET_TOKEN':
      AsyncStorage.setItem("TOKEN",action.payload)
      return { ...state, token: action.payload };
    default:
      return state;
  }
};

const GlobalProvider = ({ children }) => {
  const [state, dispatch] = useReducer(globalReducer, initialState);

  return (
    <GlobalContext.Provider value={{ state, dispatch }}>
      {children}
    </GlobalContext.Provider>
  );
};

const useGlobal = () => {
  const context = useContext(GlobalContext);
  if (!context) {
    throw new Error('useGlobal must be used within a GlobalProvider');
  }
  return context;
};

export { GlobalProvider, useGlobal ,initialState};
